package qe.spider.grab;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import qe.spider.vo.Stock;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class GrabWenCai_ZhangDieTing extends GrabWenCai {
    public GrabWenCai_ZhangDieTing(String token) {
        super(token);
    }

    public static void main(String[] args) throws IOException {
        String token = "A1_yNvt-RkXRg0JwHZvMQNOi7rjsxLtBzRO3UvGs-LZVnnGm-ZRDtt3oR_wC";
        GrabWenCai_ZhangDieTing wencai = new GrabWenCai_ZhangDieTing(token);
        String res = wencai.grab("000919,002693,601998,000705,603949最近5个交易日有过涨停或跌停吗");
        List<Stock> stocks = wencai.parseAnswer(wencai.parseAnswer(res));

        log.debug(stocks.stream().map(Stock::getStock_name).collect(Collectors.joining(",")));

    }

    public String question(List<Stock> stocks) {
        return stocks.stream().map(Stock::getStock_code).collect(Collectors.joining(",")) + "最近5个交易日有过涨停或跌停吗";
    }

    public List<Stock> parseAnswer(JsonArray answer) {
        List<Stock> stocks = new ArrayList<>();
        Iterator<JsonElement> it = answer.iterator();
        while (it.hasNext()) {
            JsonArray datas = it.next().getAsJsonObject().getAsJsonObject("data").getAsJsonArray("datas");
            Iterator<JsonElement> itd = datas.iterator();
            while (itd.hasNext()) {
                JsonObject o = itd.next().getAsJsonObject();
                String code = o.has("code") ? o.get("code").getAsString() :
                        (o.has("代码") ? o.get("代码").getAsString().split("\\.")[0] :
                                (o.has("股票代码") ? o.get("股票代码").getAsString().split("\\.")[0] : ""));
                String name = o.has("股票简称") ? o.get("股票简称").getAsString() : o.get("名称").getAsString();
                stocks.add(new Stock().code(code).name(name));
            }
        }
        return stocks;
    }


}
